package io.renren.modules.sys.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.R;


import io.renren.modules.sys.utils.HttpRequestUtil;
import io.renren.modules.sys.utils.WechatUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sys/weChat")
@Api(tags = "微信小程序")
public class getWeChatController {


    private String userJson;

    @PostMapping("getOpenId")
    @ApiOperation("获取微信openid以及用户其他信息")
    public R getOpenIdOrSession(@RequestBody Map map) {
        String code = (String) map.get("code");
        String encryptedData = (String) map.get("encryptedData");
        String iv = (String) map.get("iv");

        System.out.println("code----------" + map.get("code"));
        if (code == null || code.length() <= 0) {
            return R.ok().put("data", "code 不存在");
        }
        Map<String, Object> map2 = new HashMap<>();
        map2.put("appid", "wx010cb843dd04fff3");
        map2.put("secret", "543ddd36e749bdfd2f20be516dd0e7aa");
        map2.put("js_code", code);
        map2.put("grant_type", "authorization_code");
        JSONObject jsonObject = null;
        try {

            String response = HttpRequestUtil.httpGet("https://api.weixin.qq.com/sns/jscode2session", map2);
            jsonObject = JSON.parseObject(response);

            System.out.println(jsonObject);
            //String openId = jsonObject.getString("jsonObject");
            String sessionKey = jsonObject.getString("session_key");

            userJson = WechatUtil.decryptData(encryptedData, sessionKey, iv);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("data", userJson);
    }



    String session_id = "";

    @PostMapping("/wechatDecode")
    @ApiOperation("获取微信openid以及用户其他信息")
    public R wechatDecode(@RequestBody Map map) {
        String encryptedData = (String) map.get("encryptedData");
        String iv = (String) map.get("iv");
        WechatUtil.decryptData(encryptedData, session_id, iv);
        return R.ok().put("data", "aaaa");



    }


}
